//
//  ShippingAddressViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/7/18.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "ShippingAddressViewController.h"
#import "ShippingAddressTableViewCell.h"

#import "ShippingAddressAddViewController.h"

#import "ShippingAdressModel.h"

static NSString *addressCellID = @"addressCellID";

@interface ShippingAddressViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *addressTableView;

@property (strong, nonatomic) NSMutableArray *addressArr;

@end

@implementation ShippingAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = WhiteColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"我的收货地址";
    
    [self.view addSubview:self.addressTableView];
    __weak typeof(self) weakSelf = self;
    [self.addressTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom);
        make.top.mas_equalTo(weakSelf.view.mas_top);
    }];
    
    UIButton *addAddressBtn = [[UIButton alloc] init];
    addAddressBtn.frame = CGRectMake(0, 0, jisuan(140), jisuan(50));
    [addAddressBtn setTitle:@"添加新地址" forState:UIControlStateNormal];
    [addAddressBtn setTitle:@"添加新地址" forState:UIControlStateSelected];
    addAddressBtn.titleLabel.font = Font(24);
    [addAddressBtn setTitleColor:Color333333 forState:UIControlStateNormal];
    [addAddressBtn addTarget:self action:@selector(addAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btnIem = [[UIBarButtonItem alloc] initWithCustomView:addAddressBtn];
    self.navigationItem.rightBarButtonItem = btnIem;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addressChange:) name:@"NSNotificationChangeAddress" object:nil];
    
}

#pragma mark -地址列表
- (void)loadData {
    
    [ShippingAdressModel shippingAddressWithClassid:@"4" success:^(id responseObject) {
        
        NSLog(@"收货地址:%@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            self.addressArr = [NSMutableArray array];
            self.addressArr = responseObject[@"data"];
            [self.addressTableView reloadData];
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        
    } fail:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
        
    }];
    
    
}

- (void)showAlertViewWithIndex:(NSInteger)index {
    
    [[KYAlertView sharedInstance] showAlertView:@"提示" message:@"确定要删除么" subBottonTitle:@"确定" cancelButtonTitle:@"取消" handler:^(AlertViewClickBottonType bottonType) {
        
        if (bottonType == AlertViewClickBottonTypeSubBotton) {
            // 确定
            [self deleteAddressWithIndex:index];
            
        }else if (bottonType == AlertViewClickBottonTypeCancelButton) {
            // 取消
            
        }
        
    }];
    
}

#pragma mark -删除地址
- (void)deleteAddressWithIndex:(NSInteger)index {
    
    ShippingAdressModel *model = self.addressArr[index];
    
    NSString *par = [NSString stringWithFormat:@"{\"user_id\" : \"%@\", \"classid\" : \"%@\", \"addressid\" : \"%@\"}", [RSA encryptString:[CommonUserInfo sharedInstance].user_id publicKey:PublicKey], [RSA encryptString:@"2" publicKey:PublicKey], [RSA encryptString:model.id publicKey:PublicKey]];
    
    [PPNetworkHelper POST:@"user/Address/changeAddress" parameters:@{@"json" : par} success:^(id responseObject) {
        
        NSLog(@"删除地址:%@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            [self.addressArr removeObjectAtIndex:index];
            
            [self.addressTableView reloadData];
            
        }else {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
            
        }
        
    } failure:^(NSError *error) {
        
        if (error) {
            
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
            
        }
        
    }];
    
    
}

- (void)addressChange:(NSNotification *)notification {
    
    NSDictionary *dict = notification.object;
    NSLog(@"%@", dict);
    NSString *index = dict[@"index"];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -添加新地址
- (void)addAddressClick:(UIButton *)btn {
    
    NSLog(@"添加新地址");
    
    ShippingAddressAddViewController *addAddressVC = [[ShippingAddressAddViewController alloc] init];
    addAddressVC.title = @"添加收货地址";
    [self.navigationController pushViewController:addAddressVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return jisuan(116);
}

#pragma mark -delegate \ datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
//    return 10;
    return self.addressArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ShippingAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:addressCellID];
    
    if (!cell) {
        
        cell = [[ShippingAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addressCellID];
    
    }
    
    cell.index = indexPath.row;
    
    cell.parentVC = self;
    
    cell.shippingModel = self.addressArr[indexPath.row];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
    
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        [self showAlertViewWithIndex:indexPath.row];
        
    }
    
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return @"删除";

}


- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)){
    
    //删除
    if (@available(iOS 11.0, *)) {
        UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            
//            [self.addressArr removeObjectAtIndex:indexPath.row];        completionHandler (YES);
            
            [self showAlertViewWithIndex:indexPath.row];
            
        }];
        
//        deleteRowAction.image = [UIImage imageNamed:@"删除"];
        deleteRowAction.backgroundColor = [UIColor redColor];
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
        
        return config;
        
    }

    return nil;
    
}

#pragma mark -lazy
- (UITableView *)addressTableView {
    if (!_addressTableView) {
        
        _addressTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        
        _addressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _addressTableView.showsVerticalScrollIndicator = NO;
        _addressTableView.showsHorizontalScrollIndicator = NO;
        
        _addressTableView.estimatedRowHeight = 0;
        _addressTableView.estimatedSectionFooterHeight = 0;
        _addressTableView.estimatedSectionHeaderHeight = 0;
        
        _addressTableView.delegate = self;
        _addressTableView.dataSource = self;
        
        if (@available(iOS 11.0 , *)) {
            
            _addressTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        }
        
    }
    
    return _addressTableView;
    
}

#pragma mark -设置
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = YES;
    
    [self loadData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
//    
//    self.navigationController.navigationBar.hidden = NO;
//    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
